package com.fh.shop.api.util;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String sendPost(String url, Map<String, String> headerMap, Map<String, String> paramMap) {
        CloseableHttpClient client = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            httpPost = new HttpPost(url);
            // 设置参数
            if (headerMap != null && headerMap.size() > 0) {
                // 设置头信息
                HttpPost post = httpPost;
                headerMap.forEach((x, y) -> post.addHeader(x, y));
            }
            if (paramMap != null && paramMap.size() > 0) {
                // 设置键值对参数
                List<BasicNameValuePair> pairs = new ArrayList<>();
                paramMap.forEach((x, y) -> pairs.add(new BasicNameValuePair(x, y)));
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "utf-8");
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 发送请求
            response = client.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
